<?php





namespace app\mini\controller;





use app\crm\model\Service;

use app\mini\model\CustomerPointModel;
use think\response\Json;

use think\facade\Db;

use app\crm\model\SendMsgModel;



class ServiceLog extends Access

{



    /**

     * 商品列表

     * @return Json

     * @author Mr.Li

     * @create 2021-06-21 14:25

     */

    public function ServiceList(Service $Service): Json

    {

        $this->param = request()->param();

        $this->param['mini'] = 1;

        $customer_id = $this->param['customer_id'] ?? 0;

        // $paramArr['where'] = [['g.status','=',1],['g.is_standard_product','=',1]];

        // $paramArr['field'] = ['g.id', 'g.name', 's.price','s.small_unit_price' ,'g.image','s.item_id','s.unit_id','s.is_small_sales','s.is_big_sales'];

        // print_r($paramArr);exit;

        if($customer_id == 0){

            $data              = [];

            $data['list']      = [];

            $data['dataCount'] = 0;

        }else{

            $data              = $Service->getDataList($this->param);

        }

        return resultArray(['data' => $data]);



    }



    /**

     * 商品详情

     * @return Json

     * @author Mr.Li

     * @create 2021-06-21 14:25

     */

    public function ServiceLogList(Service $Service): Json

    {

       $this->param = request()->param();

        $this->param['customerId'] = $this->param['customer_id'] ?? 0;

        $this->param['serviceId'] = $this->param['service_id'] ?? 0;

        $data          = $Service->getLogList($this->param);

        return resultArray(['data' => $data]);

    }



    /**

     * 服务核销的时候显示的员工列表

     */

    public function readShopPersonList(Service $Service): Json

    {

       $this->param = request()->param();

       $customer_id = $this->param['customer_id'] ?? 0;

       $shopIds  = Db::name('customer')->where('id','=',$customer_id)->column('shop_id');

       $data = Db::name('shop_person')->where([['shop_id','in',$shopIds],['status','=',1]])->column('id,name');

       return resultArray(['data' => $data]);

    }

    public function readShopPersonListCS(): Json

    {

        $this->param = request()->param();

        $customer_id = $this->param['customer_id'] ?? 0;

        $staffId = $this->param['staffId'] ?? 0;

        $shopIds  = Db::name('customer')->where('id','=',$customer_id)->column('shop_id');

        $data = Db::name('shop_person')->where([['shop_id','in',$shopIds],['status','=',1]])->column('id,name');

        $staffs = [];

        foreach ($data as $key => $value) {

            if($value['id'] == $staffId){

                array_push($staffs,$value);

            }

        }

        foreach ($data as $key => $value) {

            if($value['id'] != $staffId){

                array_push($staffs,$value);

            }

        }

        return resultArray(['data' => $staffs]);

    }





    /**

     * 第一步，服务打开二位码的时候

     * @param  Service $serviceModel

     * @return Json

     */

    public function getServiceId(Service $Service): Json

    {

        $this->param = request()->param();

        $service_id = $this->param['service_id'] ?? 0;

        if($service_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }

        $returnKey = str_pad($service_id.time(),'20','0',STR_PAD_LEFT);

        $addData['service_id'] = $service_id;

        $addData['key'] = $returnKey;

        try {

            Db::name('service_log_mini_key')->insert($addData);

            return resultArray(['data' => $addData,'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }



    }



     /**

     * 第二步服务核销

     * @param  Service $serviceModel

     * @return Json

     */

    public function addServiceLog(Service $Service): Json

    {

        $this->param = request()->param();

        $this->param['user_id'] = 0;

        $this->param['pt'] = 1;

        $data = $Service->addServiceLog2($this->param);

        if (!$data) {

            return resultArray(['error' => $Service->getError()]);

        }

        return resultArray(['data' => $data,'error' => $Service->getError()]);

    }



    /**

     * 第三步的客户端

     * 客户端服务核销查询

     */

     public function getServiceKey(Service $Service): Json

    {

        $this->param = request()->param();

        $service_id = $this->param['service_id'] ?? 0;

        $key        = $this->param['key'] ?? 0;

        if($service_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }

        $where = [];

        array_push($where,['service_id','=',$service_id]);

        array_push($where,['key','=',$key]);

        try {

            $res = Db::name('service_log_mini')->where($where)->find();

            if($res){

                return resultArray(['data' => [],'error' => '获取成功']);

            }

            return resultArray(['error' => '获取失败']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

    }



    /**

     * 第四步客户端

     * 客户确认核销

     */

    public function saveServiceKey4()

    {

        $this->param = request()->param();

        $service_id = $this->param['service_id'] ?? 0;

        $key        = $this->param['key'] ?? 0;

        if($service_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }

        $where = [];

        array_push($where,['service_id','=',$service_id]);

        array_push($where,['key','=',$key]);

        try {

            $res = Db::name('service_log_mini')->where($where)->select();

            if(!$res){

                return resultArray(['error' => '无法核销，请稍后重试']);

            }

            $addData = [];

            foreach ($res as $key => $val){

                $customer_id = $val['customer_id'];

                $one = $val;

                unset($one['key']);

                unset($one['status']);

                array_push($addData,$one);

            }

            $saveCustomer['final_service'] = time();

            Db::name('customer')->where('id','=',$customer_id)->update($saveCustomer);

            $sy_num = Db::name('service_log')->where('service_id','=',$service_id)->count() ?? 0;

            $serviceInfo = Db::name('service')->where('id','=',$service_id)->find() ?? 0;

            $num = count($res);

            if (bcadd($num,$sy_num) == $serviceInfo['num']) {

                $saveData = [

                    'status'=>2,

                    'gb_end_time'=>time(),

                ];

                 $this->where('id','=',$serviceId)->save($saveData);

            }

            Db::name('service_log')->insertAll($addData);

            Db::name('service_log_mini')->where($where)->save(['status'=>1]);


            return resultArray(['data' => [],'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

    }



    /**

     * 第五部员工端刷新

     * 员工端服务完成

     */

    public function saveServiceKey5()

    {

        $this->param = request()->param();

        $service_id = $this->param['service_id'] ?? 0;

        $key        = $this->param['key'] ?? 0;

        if($service_id == 0){

            return resultArray(['error' => '正在核销，请稍后重试']);

        }

        $where = [];

        array_push($where,['service_id','=',$service_id]);

        array_push($where,['key','=',$key]);

        // array_push($where,['status','=',1]);

        try {

            $res = Db::name('service_log_mini')->where($where)->find();

            if(!$res){

                return resultArray(['error' => '正在核销，请稍后重试']);

            }

            if($res['status'] != 1){

                return resultArray(['error' => '正在核销，请稍后重试']);

            }
            return resultArray(['data' => [],'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

    }



    /**

     * 第一步，服务打开二位码的时候

     * @param  Service $serviceModel

     * @return Json

     */

    public function getServiceIds(Service $Service): Json

    {

        $this->param = request()->param();

        $customer_id = $this->param['customer_id'] ?? 0;

        if($customer_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }

        $returnKey = str_pad($customer_id.time(),'20','0',STR_PAD_LEFT);

        $addData['customer_id'] = $customer_id;

        $addData['key'] = $returnKey;

        // print_r($addData);exit;

        try {

            Db::name('service_log_mini_key')->insert($addData);

            return resultArray(['data' => $addData,'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }



    }

    /**

     * 第二部-员工端展示客户未使用的服务列表或选择的未使用的服务列表

     */

     public function getNoUseServerList(Service $Service)

     {

        $this->param = request()->param();

        $this->param['user_id'] = 0;

        $this->param['pt'] = 1;

        $this->param['mini'] = 1;

        $data = $Service->getNoUseDataList($this->param);

        if (!$data) {

            return resultArray(['error' => $Service->getError()]);

        }

        return resultArray(['data' => $data,'error' => $Service->getError()]);

     }

     /**

     * 第三步-员工端-录入核销记录并提交

     * @param  Service $serviceModel

     * @return Json

     */

    public function addServiceLogs(Service $Service): Json

    {

        $this->param = request()->param();

        $this->param['user_id'] = 0;

        $this->param['mini'] = 1;

        $data = $Service->addServiceLog3($this->param);

        if (!$data) {

            return resultArray(['error' => $Service->getError()]);

        }

        return resultArray(['data' => $data,'error' => $Service->getError()]);

    }
    public function addServiceLogs2(Service $Service): Json

    {

        $this->param = request()->param();

        $this->param['user_id'] = 0;

        $this->param['mini'] = 1;

        $data = $Service->addServiceLog4($this->param);

        if (!$data) {

            return resultArray(['error' => $Service->getError()]);

        }

        return resultArray(['data' => $data,'error' => $Service->getError()]);

    }
    public function addServiceLogs3(Service $Service): Json

    {

        $this->param = request()->param();

        $this->param['user_id'] = 0;

        $this->param['mini'] = 1;
        // $data = [];

        try{
            foreach($this->param['serviceList'] as $value)
            {
                $params = [];
                $params['customer_id'] = $this->param['customer_id'];
                $params['key'] = $this->param['key']??"";
                $params['bookId'] = $this->param['bookId'];
                $params['mark'] = $this->param['mark']?? 0;
                $params['mini'] = $this->param['mini']?? 0;
                $params['nurse_id_one'] = $value['nurse1'];
                $params['nurse_id_two'] = $value['nurse2'];
                $params['serviceList'] = [];
                array_push($params['serviceList'],$value);
                $res = $Service->addServiceLog5($params);
                if (!$res) {

                    return resultArray(['error' => $Service->getError()]);

                }
                // array_push($data,$res);
            }
        } catch (\Exception $e) {
            return resultArray(['error' => "核销失败"]);
        }
        return resultArray(['data' => ['id'=>0],'error' => $Service->getError()]);

    }

    /**
     * 核销测试接口
     */
    public function addServiceLogsCeshi(Service $Service): Json

    {


        $this->param = request()->param();

        if($this->param['customer_id']=="360956"){
            $controlList = $this->param['controlList'] ?? [];

            if($controlList){
                foreach ($controlList as $key => $value) {
                    $one = [];

                    $one['service_id'] = $value['controls_id'];
                    $one['fw_num'] = '1';
                    $one['nurse1'] = $value['nurse_id'];
                    $one['nurse2'] = '';
                    $one['type'] = '2';

                    array_push($this->param['serviceList'],$one);
                }
            }
        }

        $this->param['user_id'] = 0;

        $this->param['mini'] = 1;


        $serviceList = $this->param['serviceList'];
        $controlList = $this->param['controlList'];
        foreach($controlList as $key=>&$val){
            foreach($serviceList as $k=>&$v){
                if($val['project_name'] == $v['project_name']){
                    $v['controlList'][] = $val;
                }
            }
        }

        try{
            $customer_id = $this->param['customer_id'];

            /******3.8大促******/
            $fu_num_sum_activity = [];
            foreach($serviceList as $value)
            {
                $serviceId = $value['service_id'] ?? 0;
                $fw_num = $value['fw_num'] ?? 0;

                if($fw_num == 0){
                    throw new \Exception('服务次数不能为0');
                }

                $serviceInfo = DB::name('service')->where('id','=',$serviceId)->find();
                if (empty($serviceId) || empty($fw_num)) {
                    throw new \Exception('请录入服务记录');
                }
                $activity_id = $serviceInfo['customer_activity_id'];
                if($activity_id == 1){
                    if ($serviceInfo['use_begin_time'] > time() || $serviceInfo['use_end_time'] < time()){
                        throw new \Exception('不在使用时间内，无法进行核销');
                    }
                    array_push($fu_num_sum_activity,$fw_num);
                    $day_time = date('Ymd');
                    $map = [
                        ['activity_id','=',$activity_id],
                        ['customer_id','=',$customer_id],
                        ['goods_cancel_time','=',$day_time]
                    ];
                    $count = DB::name('activity_customer')->where($map)->count();
                    if($count>0){
                        throw new \Exception('一天只能核销一次');
                    }
                }
            }
            $activity_funum_sum = array_sum($fu_num_sum_activity);
            if($activity_funum_sum >1){
                throw new \Exception('超出活动核销次数');
            }
            /******3.8大促 ******/

            foreach($serviceList as $value)
            {
                $params = [];
                $params['customer_id'] = $this->param['customer_id'];
                $params['key'] = $this->param['key']??"";
                $params['bookId'] = $this->param['bookId'];
                $params['mark'] = $this->param['mark']?? 0;
                $params['mini'] = $this->param['mini']?? 0;

                $params['nurse_id_one'] = $value['nurse1'];
                $params['nurse_id_two'] = $value['nurse2'];

                $params['type'] = $value['type'] ?? 1;
                $params['serviceList'] = [];
                array_push($params['serviceList'],$value);
                $res = $Service->addServiceLogCeshi($params);
                if (!$res) {
                    return resultArray(['error' => $Service->getError()]);
                }
            }
        } catch (\Exception $e) {
            return resultArray(['error' => $e->getMessage()]);
        }
        return resultArray(['data' => ['id'=>0],'error' => $Service->getError()]);

    }


    /**

     * 第三步的客户端

     * 客户端服务核销查询

     */

     public function getServiceKeys(Service $Service): Json

    {

        $this->param = request()->param();

        $customer_id = $this->param['customer_id'] ?? 0;

        $key        = $this->param['key'] ?? 0;

        $mobile_model = $this->param['mobile_model'] ?? '';

        $staff_name  = $this->param['staff_name'] ?? '';

        if($customer_id == 0){

            return resultArray(['error' => '无法核销，请稍后重试']);

        }


        $where = [];

        $telephone222 = Db::name('customer')->where('id', '=', $customer_id)->value('telephone');

        $customerIds222 = Db::name('customer')->where('telephone', '=', $telephone222)->column('id');

        array_push($where, ['customer_id', 'in', $customerIds222]);

        // array_push($where,['customer_id','=',$customer_id]);

        array_push($where,['key','=',$key]);

        array_push($where,['service_type','=','1']);

        // try {

            $res = Db::name('service_log_mini')->where($where)->group('service_id')->field('service_id,count(service_id) as num,id,goods_id,nurse_id_one,nurse_id_two')->select()->toArray();

            if($res){
                $nurse_ids = [];
                $nurse_id = Db::name('service_log_mini')->where($where)->field('nurse_id_one,nurse_id_two')->select()->toArray();
                foreach($nurse_id as $kk=>$vv){
                    if(!empty($vv['nurse_id_one'])){
                        array_push($nurse_ids,$vv['nurse_id_one']);
                    }
                    if(!empty($vv['nurse_id_two'])){
                        array_push($nurse_ids,$vv['nurse_id_two']);
                    }
                }

                $list = [];
                $nurse_name = [];

                $goodsIds = array_values(array_unique(array_column($res,'goods_id')));

                $goodsList = Db::name('product_item')->where('id','in',$goodsIds)->column('name','id');

                $controlsList = Db::name('shop_person_controls')->column('name','id');

                $serviceIdArr = array_values(array_unique(array_column($res, 'service_id')));

                $service_logList = Db::name('service_log')->where('service_id','in',$serviceIdArr)->group('service_id')->column('count(service_id)', 'service_id');

                $serviceList = Db::name('service')->where('id','in',$serviceIdArr)->column('num,start_time,end_time,service_type', 'id');


//                $nurse_id_oneArr = array_values(array_unique(array_column($res, 'nurse_id_one')));
//
//                $nurse_id_twoArr = array_values(array_unique(array_column($res, 'nurse_id_two')));
//
//                $nurseArr = array_values(array_unique(array_merge($nurse_id_oneArr,$nurse_id_twoArr)));

                // print_r($nurseArr);exit;

//                $personList = Db::name('shop_person')->where('id','in',$nurseArr)->column('name', 'id');


                $nurse_name_one = '';

                $nurse_name_two = '';

                foreach ($res as $key => $val){

                    $one = [];


                    $goods_name = '';

                    $serviceData = DB::name('service')->where('id',$val['service_id'])->field('order_id,goods_id')->find();
                    if(!empty($serviceData['order_id'])){
                        $goodsInfo = DB::name('shop_order_goods')
                            ->where('order_id', $serviceData['order_id'])
                            ->where('goods_id', $serviceData['goods_id'])
                            ->field('goods_alias_name, goods_name')
                            ->find();
                        // 先判断是否存在且不为空
                    $goods_name = (!empty($goodsInfo['goods_alias_name'])) ? $goodsInfo['goods_alias_name'] : ($goodsInfo['goods_name'] ?? '');
                    }
                    $goods_name_str = '';
                    if(!empty($goods_name)){
                        $goods_name_str = $goods_name;
                    }else{
                        $goods_name_str = $goodsList[$val['goods_id']] ?? '';
                    }

                    $one['goods_name'] = $goods_name_str; // 商品名称

                    $one['benci'] = $val['num']; // 本次使用次数

                    $one['sy_num']       = $service_logList[$val['service_id']] ?? 0; // 历史使用

                    $zong = $serviceList[$val['service_id']] ?? [];

                    // print_r($serviceList);

                    // print_r($val);

                    // exit;

                    $zongnum = $zong['num'] ?? 0;

                    $one['yy_num']       = bcsub($zongnum,$one['sy_num']); // 未使用

                    $one['yy_num'] = $one['yy_num'] < 0 ? 0 : $one['yy_num'] ;

                    $start_time = $zong['start_time'] ?? 0;

                    $end_time = $zong['end_time'] ?? 0;

                    $one['start_time'] = $start_time > 0 ? date('Y-m-d H:i:s',$zong['start_time']) : ''; // 开始时间

                    $one['end_time'] = $end_time > 0 ? date('Y-m-d H:i:s',$zong['end_time']) : ''; // 结束时间

                    $one['service_type'] = $zong['service_type'] ?? 0; // 服务类型 1按时间 2按次数

                    $one['mobile_model'] =$mobile_model;
                    $one['staff_name'] =$staff_name;

//                    $nurse_name_one = $personList[$val['nurse_id_one']] ?? ''; // 一号护理师
//
//                    $nurse_name_two = $personList[$val['nurse_id_two']] ?? ''; // 二号护理师

                    array_push($list,$one);

                }
                $nurse_name_one = '';
                $nurse_name_two = '';
                if(empty($list)){
                    return resultArray(['error' => '获取失败.']);
                }
                $nurse_ids = array_unique($nurse_ids);
                $personList = Db::name('shop_person')->where('id','in',$nurse_ids)->column('name');
                $nurse_name = implode('、', $personList);

                return resultArray(['data' => ['list'=>$list,'nurse_name_one'=>$nurse_name_one,'nurse_name_two'=>$nurse_name_two,'nurse_name'=>$nurse_name],'error' => '获取成功']);

            }

            return resultArray(['error' => '获取失败..']);

        // } catch (Exception $e) {

        //     return resultArray(['error' => '系统繁忙请稍后重试']);

        // }

    }



    /**
     * 第四步客户端
     * 客户确认核销
     */
    public function saveServiceKeys4()
    {
        $this->param = request()->param();
        $customer_id = $this->param['customer_id'] ?? 0;
        $key = $this->param['key'] ?? 0;
        $bookId = $this->param['bookId'] ?? 0;
        $mobile_model = $this->param['mobile_model'] ?? '';
        $staff_name = $this->param['staff_name'] ?? '';

        if ($customer_id == 0) {
            return resultArray(['error' => '无法核销，请稍后重试']);
        }

        // 获取客户信息
        $customer = Db::name('customer')
            ->where('id', $customer_id)
            ->field('telephone,shop_id')
            ->find();
        $customerIds = Db::name('customer')
            ->where('telephone', $customer['telephone'])
            ->column('id');

        // Db::startTrans();
        // try {
            // 获取需要核销的服务日志
            $where = [
                ['customer_id', 'in', $customerIds],
                ['key', '=', $key]
            ];
            $res = Db::name('service_log_mini')
                ->where($where)
                ->select()
                ->toArray();

            if (!$res) {
                return resultArray(['error' => '无法核销，请稍后重试']);
            }

            // 按service_id分组
            $groupedServices = [];
            foreach ($res as $item) {
                $groupedServices[$item['service_id']][] = $item;
            }

            $serviceIds = array_keys($groupedServices);
            $serviceModel = new Service();

            // 预加载服务数据
            $servicesData = Db::name('service')
                ->where('id', 'in', $serviceIds)
                ->column('*', 'id');

            // 预加载各服务的已核销次数
            $cancelCounts = Db::name('service_log')
                ->where('service_id', 'in', $serviceIds)
                ->where('is_cancel', 0)
                ->group('service_id')
                ->column('count(id)', 'service_id');

            foreach ($groupedServices as $serviceId => $logs)
            {
                $serviceData = $servicesData[$serviceId] ?? null;
                if (!$serviceData) continue;

                $num = count($logs); // 本次核销次数
                $alreadyCancelCount = $cancelCounts[$serviceId] ?? 0; // 已核销次数
                $needNoZeroNum = $this->calculateNeedNoZeroNum($serviceData, $alreadyCancelCount);

                // 处理延期服务
                if ($serviceData['overtime_num'] > 0) {
                    $serviceData = $this->handleOvertimeService($serviceData, $customer_id);
                }

                // 计算消耗金额
                list($consumeMoney, $consumeGratuity, $lastTimeMoney, $lastTimeGift,$onceDiscountAmount,$lastDiscountAmount,$onceRealCancelBalance,$onceRealCancelGift,$lastRealCancelBalance,$lastRealCancelGift) =
                    $serviceModel->lasttimeConsume($serviceData);

                // 处理每月核销限制
                $isCurrentMonth = (date('Ym', $serviceData['end_time']) == date('Ym'));
                $consumeParams = [
                    'num' => $num,
                    'needNoZeroNum' => $needNoZeroNum,
                    'consumeMoney' => $consumeMoney,
                    'consumeGratuity' => $consumeGratuity,
                    'lastTimeMoney' => $lastTimeMoney,
                    'lastTimeGift' => $lastTimeGift,
                    'onceDiscountAmount' =>$onceDiscountAmount,
                    'lastDiscountAmount'=>$lastDiscountAmount,
                    'onceRealCancelBalance'=>$onceRealCancelBalance,
                    'onceRealCancelGift'=>$onceRealCancelGift,
                    'lastRealCancelBalance'=>$lastRealCancelBalance,
                    'lastRealCancelGift'=>$lastRealCancelGift,
                    'serviceMoney' => $serviceData['consume_money'],
                    'serviceGratuity' => $serviceData['consume_gratuity'],
                    'alreadyCancelCount' => $alreadyCancelCount,
                    'isCurrentMonth' => $isCurrentMonth,
                    'serviceType' => $serviceData['service_type']
                ];

                // 插入核销记录
                foreach ($logs as $index => $log) {
                    $consumeAmounts = $this->calculateConsumeAmounts($index, $consumeParams);

                    $serviceLogId = $this->insertServiceLog([
                        'log' => $log,
                        'serviceId' => $serviceId,
                        'bookId' => $bookId,
                        'mobile_model' => $mobile_model,
                        'staff_name' => $staff_name,
                        'consumeMoney' => $consumeAmounts['money'],
                        'consumeGratuity' => $consumeAmounts['gratuity'],

                        'discountAmount' => $consumeAmounts['discount_amount'],
                        'realCancelBalance' => $consumeAmounts['real_cancel_balance'],
                        'realCancelGift' => $consumeAmounts['real_cancel_gift'],

                        // 修正这里：使用当前服务的$serviceData
                        'category_type_one' => $serviceData['category_type_one'],
                        'category_type_two' => $serviceData['category_type_two'],
                        'category_type_three' => $serviceData['category_type_three']
                    ]);

                    // 插入护理师服务项
                    $this->insertNurseControls($log, $serviceLogId, $serviceId);
                }

                // 更新服务状态
                if (($alreadyCancelCount + $num) >= $serviceData['num']) {
                    Db::name('service')->where('id', $serviceId)->update([
                        'status' => 2,
                        'gb_end_time' => time()
                    ]);
                }
            }

            // 更新客户最后服务时间
            Db::name('customer')->where('id', $customer_id)->update([
                'final_service' => time()
            ]);

            // 更新核销状态
            Db::name('service_log_mini')->where($where)->update(['status' => 1]);
            Db::name('books')->where('id', $bookId)->update([
                'is_use' => 1,
                'is_use_time' => time()
            ]);
            Db::name('books_uselog')->where('book_id', $bookId)->update([
                'customer_id' => $customer_id,
                'customer_time' => time()
            ]);

            // 积分变动
            CustomerPointModel::pointChange($customer_id, 3);

            Db::commit();
            return resultArray(['data' => [], 'error' => '获取成功']);
        // } catch (\Exception $e) {
        //     Db::rollback();
        //     return resultArray(['error' => '系统繁忙请稍后重试']);
        // }
    }

    /**
     * 计算需要非零消耗的次数
     */
    private function calculateNeedNoZeroNum($serviceData, $alreadyCancelCount)
    {
        if ($serviceData['service_type'] == 1) { // 疗程卡
            $monthStart = $serviceData['overtime_num'] > 0
                ? $serviceData['start_time']
                : strtotime(date('Y-m-01'));
            $monthEnd = strtotime(date('Y-m-t 23:59:59'));

            $monthCancelCount = Db::name('service_log')
                ->where('service_id', $serviceData['id'])
                ->where('create_time', 'between', [$monthStart, $monthEnd])
                ->where('is_cancel', 0)
                ->count();

            return $serviceData['num'] - $monthCancelCount;
        }

        // 次卡
        return $serviceData['num'] - $alreadyCancelCount;
    }

    /**
     * 处理延期服务
     */
    private function handleOvertimeService($serviceData, $customerId)
    {
        $map = [
            ['customer_id', '=', $customerId],
            ['service_id', '=', $serviceData['id']]
        ];
        $overtime = Db::name('service_overtime_log')
            ->where($map)
            ->order('id', 'desc')
            ->find();

        if ($overtime) {
            $serviceData['consume_gratuity'] = $overtime['consume_gratuity'];
            $serviceData['service_max_num'] = $overtime['service_max_num'];
            $serviceData['consume_money'] = $overtime['consume_money'];
            $serviceData['first_month_max_service_num'] = $overtime['first_month_max_service_num'];
            $serviceData['middle_month_max_service_num'] = $overtime['middle_month_max_service_num'];
            $serviceData['end_month_max_service_num'] = $overtime['end_month_max_service_num'];
            $serviceData['start_time'] = $overtime['new_begin_time'];
            $serviceData['end_time'] = $overtime['new_end_time'];
        }

        return $serviceData;
    }

    /**
     * 计算消耗金额
     */
    private function calculateConsumeAmounts_zantingshiyong($index, $params)
    {
        $result = ['money' => 0, 'gratuity' => 0];
        $currentNum = $index + 1;

        // 最后一个月特殊处理
        if ($params['isCurrentMonth']) {
            if ($params['needNoZeroNum'] == 1) {
                if ($currentNum <= 1) {
                    $result['money'] = $this->getMoneyValue(
                        $params['consumeMoney'],
                        $params['serviceMoney'],
                        $params['lastTimeMoney'],
                        $params['alreadyCancelCount']
                    );
                    $result['gratuity'] = $this->getMoneyValue(
                        $params['consumeGratuity'],
                        $params['serviceGratuity'],
                        $params['lastTimeGift'],
                        $params['alreadyCancelCount']
                    );
                }
            } else {
                if ($currentNum < $params['needNoZeroNum']) {
                    $result['money'] = $this->getMoneyValue(
                        $params['consumeMoney'],
                        $params['serviceMoney'],
                        $params['lastTimeMoney'],
                        $params['alreadyCancelCount']
                    );
                    $result['gratuity'] = $this->getMoneyValue(
                        $params['consumeGratuity'],
                        $params['serviceGratuity'],
                        $params['lastTimeGift'],
                        $params['alreadyCancelCount']
                    );
                } elseif ($currentNum == $params['needNoZeroNum']) {
                    $result['money'] = $params['lastTimeMoney'];
                    $result['gratuity'] = $params['lastTimeGift'];
                }
            }
            return $result;
        }

        // 非最后一个月处理
        if ($params['serviceType'] == 1) { // 疗程卡
            if ($params['needNoZeroNum'] == 1) {
                if ($currentNum <= 1) {
                    $result['money'] = $this->getMoneyValue(
                        $params['consumeMoney'],
                        $params['serviceMoney'],
                        $params['lastTimeMoney'],
                        $params['alreadyCancelCount']
                    );
                    $result['gratuity'] = $this->getMoneyValue(
                        $params['consumeGratuity'],
                        $params['serviceGratuity'],
                        $params['lastTimeGift'],
                        $params['alreadyCancelCount']
                    );
                }
            } else {
                if ($currentNum <= $params['needNoZeroNum']) {
                    $result['money'] = $this->getMoneyValue(
                        $params['consumeMoney'],
                        $params['serviceMoney'],
                        $params['lastTimeMoney'],
                        $params['alreadyCancelCount']
                    );
                    $result['gratuity'] = $this->getMoneyValue(
                        $params['consumeGratuity'],
                        $params['serviceGratuity'],
                        $params['lastTimeGift'],
                        $params['alreadyCancelCount']
                    );
                }
            }
        } else { // 次卡
            if ($params['needNoZeroNum'] == 1) {
                $result['money'] = $params['alreadyCancelCount'] > 0
                    ? $params['lastTimeMoney']
                    : ($params['consumeMoney'] < 0.01 && $params['serviceMoney'] != 0
                        ? 0
                        : $params['lastTimeMoney']);

                $result['gratuity'] = $params['alreadyCancelCount'] > 0
                    ? $params['lastTimeGift']
                    : ($params['consumeGratuity'] < 0.01 && $params['serviceGratuity'] != 0
                        ? 0
                        : $params['lastTimeGift']);
            } else {
                if ($currentNum < $params['needNoZeroNum']) {
                    $result['money'] = $this->getMoneyValue(
                        $params['consumeMoney'],
                        $params['serviceMoney'],
                        $params['lastTimeMoney'],
                        $params['alreadyCancelCount']
                    );
                    $result['gratuity'] = $this->getMoneyValue(
                        $params['consumeGratuity'],
                        $params['serviceGratuity'],
                        $params['lastTimeGift'],
                        $params['alreadyCancelCount']
                    );
                } elseif ($currentNum == $params['needNoZeroNum']) {
                    $result['money'] = $params['lastTimeMoney'];
                    $result['gratuity'] = $params['lastTimeGift'];
                }
            }
        }

        return $result;
    }

    /**
     * 计算消耗金额--仅有次卡
     */
    private function calculateConsumeAmounts($index, $params)
    {
        $result = ['money' => 0, 'gratuity' => 0, 'discount_amount' =>0,'real_cancel_balance'=>0,'real_cancel_gift'=>0];
        $currentNum = $index + 1;

        if($params['needNoZeroNum'] == 1){
            $result['money'] = $params['lastTimeMoney'];
            $result['gratuity'] = $params['lastTimeGift'];
            $result['discount_amount'] = $params['lastDiscountAmount'];
            $result['real_cancel_balance'] = $params['lastRealCancelBalance'];
            $result['real_cancel_gift'] = $params['lastRealCancelGift'];
        }

        else{
            if($currentNum < $params['needNoZeroNum']){
                $result['money'] = $params['consumeMoney'];
                $result['gratuity'] = $params['consumeGratuity'];

                $result['discount_amount'] = $params['onceDiscountAmount'];
                $result['real_cancel_balance'] = $params['onceRealCancelBalance'];
                $result['real_cancel_gift'] = $params['onceRealCancelGift'];
            }

            elseif($currentNum == $params['needNoZeroNum']){
                $result['money'] = $params['lastTimeMoney'];
                $result['gratuity'] = $params['lastTimeGift'];
                $result['discount_amount'] = $params['lastDiscountAmount'];
                $result['real_cancel_balance'] = $params['lastRealCancelBalance'];
                $result['real_cancel_gift'] = $params['lastRealCancelGift'];
            }
        }

        return $result;
    }


    /**
     * 获取合理的金额值
     */
    private function getMoneyValue($consume, $service, $lastTime, $alreadyCount)
    {
        if ($consume < 0.01 && $service != 0) {
            return $alreadyCount > 0 ? 0 : $lastTime;
        }
        return $consume;
    }

    /**
     * 插入服务日志
     */
    private function insertServiceLog($params)
    {
        $data = [
            'mobile_model' => $params['mobile_model'],
            'station_name' => $params['staff_name'],
            'book_id' => $params['bookId'],
            'service_id' => $params['serviceId'],
            'nurse_id_one' => $params['log']['nurse_id_one'] ?? 0,
            'nurse_id_two' => $params['log']['nurse_id_two'] ?? 0,
            'start_time' => $params['log']['start_time'],
            'end_time' => $params['log']['end_time'],
            'mark' => $params['log']['mark'],
            'comment_time' => 0,
            'create_time' => $params['log']['create_time'],
            'customer_id' => $params['log']['customer_id'] ?? 0,
            'shop_id' => $params['log']['shop_id'],
            'pt' => 1,
            'goods_id' => $params['log']['goods_id'] ?? 0,
            'consume_money' => $params['consumeMoney'],
            'consume_gratuity' => $params['consumeGratuity'],

            'discount_amount'  =>$params['discountAmount'],
            'real_cancel_balance'  =>$params['realCancelBalance'],
            'real_cancel_gift'  =>$params['realCancelGift'],

            'item_one' => $params['category_type_one'] ?? '',
            'item_two' => $params['category_type_two'] ?? '',
            'item_three' => $params['category_type_three'] ?? ''
        ];

        return Db::name('service_log')->insertGetId($data);
    }

    /**
     * 插入护理师服务项
     */
    private function insertNurseControls($log, $serviceLogId, $serviceId)
    {
        if (empty($log['control_str'])) return;

        $controls = json_decode($log['control_str'], true);
        if (empty($controls)) return;

        $insertData = [];
        $time = time();

        foreach ($controls as $group) {
            foreach ($group['controls_id'] as $item) {
                $insertData[] = [
                    'shop_id' => $log['shop_id'],
                    'service_id' => $serviceId,
                    'service_log_id' => $serviceLogId,
                    'nurse_id' => $group['nurse_id'],
                    'service_item' => $item,
                    'create_time' => $time
                ];
            }
        }

        if (!empty($insertData)) {
            Db::name('service_log_control')->insertAll($insertData);
        }
    }



    /**
     * 第五部员工端刷新
     * 员工端服务完成
     */

    public function saveServiceKeys5()

    {

        $this->param = request()->param();

        $customer_id = $this->param['customer_id'] ?? 0;

        $key        = $this->param['key'] ?? 0;

        if($customer_id == 0){

            return resultArray(['error' => '正在核销，请稍后重试']);

        }

        $where = [];

        $telephone222 = Db::name('customer')->where('id', '=', $customer_id)->value('telephone');

        $customerIds222 = Db::name('customer')->where('telephone', '=', $telephone222)->column('id');

        array_push($where,['customer_id','in',$customerIds222]);

        array_push($where,['key','=',$key]);

        array_push($where,['status','=',1]);

        try {

            $res = Db::name('service_log_mini')->where($where)->find();

            if(!$res){

                return resultArray(['error' => '正在核销，请稍后重试']);

            }

            if($res['status'] != 1){

                return resultArray(['error' => '正在核销，请稍后重试']);

            }

            return resultArray(['data' => [],'error' => '获取成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '系统繁忙请稍后重试']);

        }

    }



    public function smallProject(){

        $smallProject = DB::name('shop_person_controls')->where('status',1)->cache(true,60)->field('id,name,type')->select()->toArray();
        return resultArray(['data' => $smallProject,'error' => '获取成功']);
    }

        /**

     * 客户评论

     */

    public function comment()

    {

        $this->param = request()->param();

        $service_log_id = $this->param['service_log_id'] ?? 0;

        $fraction       = $this->param['fraction'] ?? '';

        $describe       = $this->param['describe'] ?? '';

        if($service_log_id == 0){

            return resultArray(['error' => '请选择评价的服务记录']);

        }

        if ($fraction === '') {

            return resultArray(['error' => '请对该次服务进行评分']);

        }

        $where = [];

        array_push($where,['id','=',$service_log_id]);

        $add['fraction'] = $fraction;

        $add['describe'] = $describe;

        $add['comment_time'] = time();

        try {

            Db::name('service_log')->where($where)->update($add);

            return resultArray(['data' => [],'error' => '评论提交成功']);

        } catch (Exception $e) {

            return resultArray(['error' => '评论提交失败']);

        }

    }

}

